const puppeteer = require("puppeteer");
const fs = require("fs");
const path = require("path");

// 确保PDF目录存在
const pdfDir = path.join(__dirname, "pdfs");
if (!fs.existsSync(pdfDir)) {
  fs.mkdirSync(pdfDir, { recursive: true });
}

// 生成PDF文件
async function generatePdf(url, options = {}) {
  const browser = await puppeteer.launch({
    headless: "new",
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });
  const page = await browser.newPage();

  await page.goto(url, { waitUntil: "networkidle0" });

  const pdfOptions = {
    path: options.outputPath,
    format: options.format || "A4",
    printBackground: options.printBackground || true,
    margin: options.margin || {},
  };

  const pdfBuffer = await page.pdf(pdfOptions);
  await browser.close();

  return pdfBuffer;
}

// 将URL转换为PDF并保存
async function urlToPdf(url, filename) {
  const outputPath = path.join(pdfDir, filename);
  try {
    await generatePdf(url, { outputPath });
    return { success: true, path: outputPath, filename };
  } catch (error) {
    console.error("PDF生成错误:", error);
    return { success: false, error: error.message };
  }
}

// 注册PDF相关路由到Express应用
function registerPdfRoutes(app) {
  /**
   * PDF下载
   */
  app.get("/pdfs/:filename", (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join(pdfDir, filename);

    if (fs.existsSync(filePath)) {
      res.download(filePath);
    } else {
      res.status(404).json({ error: "PDF文件不存在" });
    }
  });

  /**
   * 将URL转换为PDF
   */
  app.post("/api/url-to-pdf", async (req, res) => {
    const { url, filename } = req.body;

    if (!url || !filename) {
      return res.status(400).json({ error: "缺少必要参数" });
    }

    try {
      const result = await urlToPdf(url, filename);
      if (result.success) {
        res.json({
          success: true,
          downloadUrl: `/pdfs/${filename}`,
          message: "PDF已生成",
        });
      } else {
        res.status(500).json({ error: result.error });
      }
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });
}

module.exports = {
  generatePdf,
  urlToPdf,
  registerPdfRoutes,
};
